package com.example.wordapp.aop;


import com.alibaba.fastjson.JSONObject;
import com.example.wordapp.annotation.MyLog;
import com.example.wordapp.utils.IpAddressUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect //切面类
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LogMapper logMapper;

    @Around("@annotation(com.example.wordapp.annotation.MyLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {


        //操作的IP
        String ipAddress = IpAddressUtil.getIpAddress(request);
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作的方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法传入的参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        // 调用原始目标方法运行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        //方法执行的返回值
        String returnValue = JSONObject.toJSONString(result);
        //方法执行耗时
        Long costTime = end - begin;

        // 描述信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        MyLog annotation = signature.getMethod().getAnnotation(MyLog.class);
        String title = annotation.title();

        // 记录操作日志
        Log myLog = new Log(null, ipAddress, operateTime, className, methodName, methodParams, returnValue, costTime, title);

        logMapper.insert(myLog);
        return result;
    }
}
